package persistence

import (
	"github.com/yejingxuan/accumulate/domain/entity"
	"gorm.io/gorm"
)

type klinePersis struct {
	db *gorm.DB
}

func NewKlinePersis(db *gorm.DB) *klinePersis {
	return &klinePersis{db}
}

//创建或者更新kline数据
func (k klinePersis) CreateOrUpdateKlineInfo(kline *entity.Kline) error {
	exist, err := k.GetKlineInfoByCode(kline.Symbol)
	if exist.Kline != "" {
		param := map[string]interface{}{
			"kline": kline.Kline,
		}
		err = k.db.Table(entity.TableKline).Where("symbol = ?", kline.Symbol).Updates(param).Error
		return err
	} else {
		err := k.db.Table(entity.TableKline).Create(kline).Error
		return err
	}
}

//删除所有的kline数据
func (k klinePersis) DelAllKline() error {
	return k.db.Debug().Table(entity.TableKline).Where("1=1").Delete(nil).Error
}

//获取kline信息
func (k klinePersis) GetKlineInfoByCode(code string) (*entity.Kline, error) {
	res := entity.Kline{}
	err := k.db.Table(entity.TableKline).Where("symbol = ?", code).Scan(&res).Error
	return &res, err
}

//分页获取kline信息
func (k klinePersis) GetKlinePageInfo(pageSize int, pageNo int) ([]entity.Kline, int, error) {
	var data []entity.Kline
	var count int64

	err := k.db.Table(entity.TableKline).Order("symbol asc").Limit(pageSize).Offset((pageNo - 1) * pageSize).Find(&data).Error
	if err != nil {
		return data, int(count), err
	}

	err = k.db.Table(entity.TableKline).Count(&count).Error
	return data, int(count), err
}
